/*************************************************************************
    > File Name: client.cpp
    > Author: Lancer
    > Mail: 18826075768@163.com
************************************************************************/

#include <iostream>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define CUSTOMER_NUM 10

using namespace std;

sem_t sem;
void* get_service(void* thread_id){
    int customer_id = *(int*)thread_id;
    if(sem_wait(&sem) == 0){
        usleep(2000);
        printf("customer %d receive service ...\n", customer_id);
        sem_post(&sem);
    }
}
int main(){
    sem_init(&sem, 0, 2);
    pthread_t customers[CUSTOMER_NUM];
    int i, ret;
    for(i = 0; i < CUSTOMER_NUM;  i++){
        int customer_id = i;
        ret =pthread_create(&customers[i], NULL, get_service, &customer_id);
        if(ret){
            perror("pthread create ");
        }
        else{
            printf("Customer %d arrived!\n", i);
        }
        usleep(1500);
    }

    sleep(20);
    int j;
    for(j = 0; i < CUSTOMER_NUM; j++){
        pthread_join(customers[i], NULL);
    }
    sem_destroy(&sem);
    return 0;
}